//Given a signed 32-bit integer x, return x with its digits reversed. If reversi
//ng x causes the value to go outside the signed 32-bit integer range [-231, 231 -1], then return 0.
// Assume the environment does not allow you to store 64-bit integers (signed or
// unsigned). 
//
// 
// Example 1: 
// Input: x = 123
//Output: 321
// Example 2: 
// Input: x = -123
//Output: -321
// Example 3: 
// Input: x = 120
//Output: 21
// Example 4: 
// Input: x = 0
//Output: 0
// 
// 
// Constraints: 
//
// 
// -231 <= x <= 231 - 1 
// 
// Related Topics 数学 
// 👍 2792 👎 0


package leetcode.editor.cn;

//Java：Reverse Integer
class P7ReverseInteger {
    public static void main(String[] args) {
        Solution solution = new P7ReverseInteger().new Solution();
        // TO TEST
        System.out.println(solution.reverse(1534236469));

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int reverse(int x) {
            int sum = 0;
            while (x != 0) {
                if (sum < Integer.MIN_VALUE / 10 || sum > Integer.MAX_VALUE / 10) {
                    return 0;
                }
                sum = sum * 10 + x % 10;
                x = x / 10;
            }
            return sum;
        }
        public  int reverseStr(int x) {

            if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE || x == 0) {
                return 0;
            }
            int signed = 1;
            if (x < 0) {
                signed = -1;
            }
            StringBuilder str = new StringBuilder(String.valueOf(x * signed));
            int count = 0;//0的数量
            boolean flag = true;
            for (int i = str.length() - 1; i >= 0 & flag; i--) {
                if (str.charAt(i) != '0') {
                    flag = false;
                    continue;
                }
                count++;
            }
            str = new StringBuilder(str.substring(0, str.length() - count));
    /*    System.out.println(str.length());
        System.out.println(str.length()/2);*/
            for (int i = 0; i < (str.length() / 2); i++) {
                char a = str.charAt(i);
                char b = str.charAt(str.length() - i - 1);
                str.replace(i, i + 1, String.valueOf(b));
                str.replace(str.length() - i - 1, str.length() - i, String.valueOf(a));
            }
            int l = Integer.parseInt(str.toString()) * signed;
            return l;

        }
    }

//leetcode submit region end(Prohibit modification and deletion)

}